package com.evaluation.controller;

import com.evaluation.common.Result;
import com.evaluation.entity.IndicatorsWf;
import com.evaluation.service.IndicatorsWfService;
import com.evaluation.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考核指标权重管理Controller
 */
@RestController
@RequestMapping("/api/admin")
public class AdminIndicatorsWeightController {

    @Autowired
    private IndicatorsWfService indicatorsWfService;

    /**
     * 获取所有指标权重（无分页）
     */
    @GetMapping("/indicator-weights")
    public Result<List<IndicatorsWf>> getAllIndicatorWeights() {
        try {
            List<IndicatorsWf> list = indicatorsWfService.list();
            return Result.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取指标权重列表失败");
        }
    }

    /**
     * 获取指标权重列表（分页）
     */
    @GetMapping("/indicator-weights/list")
    public Result<Map<String, Object>> getIndicatorWeights(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String weightName,
            @RequestParam(required = false) String evaluationType) {

        try {
            // 构建查询条件
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<IndicatorsWf> queryWrapper =
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();

            if (weightName != null && !weightName.trim().isEmpty()) {
                queryWrapper.like("QZMC", weightName.trim());
            }

            if (evaluationType != null && !evaluationType.trim().isEmpty()) {
                queryWrapper.eq("CPLX", evaluationType.trim());
            }

            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<IndicatorsWf> pageParam =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<IndicatorsWf> result =
                    indicatorsWfService.page(pageParam, queryWrapper);

            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", result.getCurrent());
            data.put("size", result.getSize());

            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取指标权重列表失败");
        }
    }

    /**
     * 新增指标权重
     */
    @PostMapping("/indicator-weights")
    public Result<String> addIndicatorWeight(@RequestBody IndicatorsWf indicatorsWf) {
        try {
            // 验证必填字段
            if (indicatorsWf.getQzmc() == null || indicatorsWf.getQzmc().trim().isEmpty()) {
                return Result.error("权重名称不能为空");
            }
            
            // 检查权重名称是否已存在
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<IndicatorsWf> nameQueryWrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            nameQueryWrapper.eq("QZMC", indicatorsWf.getQzmc().trim());
            IndicatorsWf existingByName = indicatorsWfService.getOne(nameQueryWrapper);
            if (existingByName != null) {
                return Result.error("权重名称已存在");
            }
            
            // 如果编号为空，自动生成编号
            if (indicatorsWf.getQzbh() == null || indicatorsWf.getQzbh().trim().isEmpty()) {
                indicatorsWf.setQzbh(generateWeightId());
            } else {
                // 检查权重编号是否已存在
                IndicatorsWf existingWeight = indicatorsWfService.getById(indicatorsWf.getQzbh().trim());
                if (existingWeight != null) {
                    return Result.error("权重编号已存在");
                }
            }
            
            // 设置字段值
            indicatorsWf.setQzmc(indicatorsWf.getQzmc().trim());
            if (indicatorsWf.getQzbh() != null) {
                indicatorsWf.setQzbh(indicatorsWf.getQzbh().trim());
            }
            
            // 设置默认测评类型
            if (indicatorsWf.getCplx() == null || indicatorsWf.getCplx().trim().isEmpty()) {
                indicatorsWf.setCplx("0"); // 默认对教师
            }

            boolean success = indicatorsWfService.save(indicatorsWf);
            if (success) {
                return Result.success("新增指标权重成功");
            } else {
                return Result.error("新增指标权重失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增指标权重失败：" + e.getMessage());
        }
    }

    /**
     * 根据权重编号查询指标权重详情
     */
    @GetMapping("/indicator-weights/{qzbh}")
    public Result<IndicatorsWf> getIndicatorWeightDetail(@PathVariable String qzbh) {
        try {
            IndicatorsWf indicatorsWf = indicatorsWfService.getById(qzbh);
            if (indicatorsWf == null) {
                return Result.error("指标权重不存在");
            }
            return Result.success(indicatorsWf);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询指标权重详情失败");
        }
    }

    /**
     * 更新指标权重
     */
    @PutMapping("/indicator-weights/{qzbh}")
    public Result<String> updateIndicatorWeight(@PathVariable String qzbh, @RequestBody IndicatorsWf indicatorsWf) {
        try {
            indicatorsWf.setQzbh(qzbh);
            boolean success = indicatorsWfService.updateById(indicatorsWf);
            if (success) {
                return Result.success("更新指标权重成功");
            } else {
                return Result.error("更新指标权重失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新指标权重失败");
        }
    }

    /**
     * 删除指标权重
     */
    @DeleteMapping("/indicator-weights/{qzbh}")
    public Result<String> deleteIndicatorWeight(@PathVariable String qzbh) {
        try {
            boolean success = indicatorsWfService.removeById(qzbh);
            if (success) {
                return Result.success("删除指标权重成功");
            } else {
                return Result.error("删除指标权重失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除指标权重失败");
        }
    }

    /**
     * 导入指标权重数据
     */
    @PostMapping("/indicator-weights/import")
    public Result<Map<String, Object>> importIndicatorWeights(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 使用ExcelUtil读取Excel文件
            List<IndicatorsWf> dataList = ExcelUtil.readExcel(file, IndicatorsWf.class);

            int successCount = 0;
            int errorCount = 0;

            for (IndicatorsWf weight : dataList) {
                try {
                    // 设置默认值
                    if (weight.getQzbh() == null || weight.getQzbh().trim().isEmpty()) {
                        weight.setQzbh(generateWeightId());
                    }
                    if (weight.getCplx() == null) {
                        weight.setCplx("0"); // 默认对教师
                    }

                    indicatorsWfService.save(weight);
                    successCount++;
                } catch (Exception e) {
                    errorCount++;
                    e.printStackTrace();
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("total", dataList.size());
            result.put("success", successCount);
            result.put("error", errorCount);

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入指标权重数据失败：" + e.getMessage());
        }
    }

    /**
     * 导出指标权重数据
     */
    @GetMapping("/indicator-weights/export")
    public void exportIndicatorWeights(HttpServletResponse response) {
        try {
            List<IndicatorsWf> list = indicatorsWfService.list();
            List<Map<String, Object>> exportData = new ArrayList<>();

            for (IndicatorsWf weight : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("权重编号", weight.getQzbh());
                map.put("权重名称", weight.getQzmc());
                map.put("权重", weight.getQz());
                map.put("测评类型", weight.getCplx().equals("0") ? "对教师" : "对部门");

                exportData.add(map);
            }

            if (!exportData.isEmpty()) {
                ExcelUtil.exportExcel(response, "指标权重数据", exportData);
            } else {
                // 创建空Excel
                exportData.add(new HashMap<String, Object>() {{
                    put("权重编号", "");
                    put("权重名称", "");
                    put("权重", "");
                    put("测评类型", "");
                }});
                ExcelUtil.exportExcel(response, "指标权重数据", exportData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String generateWeightId() {
        IndicatorsWf maxRecord = indicatorsWfService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<IndicatorsWf>().orderByDesc("QZBH").last("LIMIT 1"));
        if (maxRecord != null && maxRecord.getQzbh() != null) {
            try {
                int maxId = Integer.parseInt(maxRecord.getQzbh());
                return String.valueOf(maxId + 1);
            } catch (NumberFormatException e) {
                return "1";
            }
        }
        return "1";
    }
}
